# 维修订单服务
from models import db, RepairOrder, UserAddress, User
from common.response import APIResponse
from common.orders import generate_order_id
from stateMachine.machine import OrderStateMachine
from datetime import datetime

class RepairOrderService:
    @staticmethod
    def get_user_order_stats(user_id, master_id):
        # 查询用户的所有订单
        if master_id:
            orders = RepairOrder.query.filter_by(tech_id=master_id).all()
        elif user_id:
            orders = RepairOrder.query.filter_by(user_id=user_id).all()
        else:
            orders = RepairOrder.query.all()
        if not orders:
            return APIResponse.success({'total': 0, 'completed': 0, 'today': 0})

        # 统计订单状态
        total = len(orders)
        completed = sum(1 for order in orders if order.status == 5) 
        today = sum(1 for order in orders if order.created_at.date() == datetime.now().date())

        return APIResponse.success({
            'total': total,
            'completed': completed,
            'today': today
        })

    @staticmethod
    def get_order_by_id(order_id):
        order = RepairOrder.query.filter_by(id=order_id).first()
        if not order:
            return APIResponse.not_found('Order not found')
        return APIResponse.success(order.to_dict())

    @staticmethod
    def get_orders_by_user_id(user_id):
        orders = RepairOrder.query.filter_by(user_id=user_id).all()
        return APIResponse.success([order.to_dict() for order in orders])

    @staticmethod
    def get_all_orders(args):
        # 连表查询，需要分页
        page = args.get('page', 1, type=int)
        per_page = args.get('pageSize', 10, type=int)
        status = args.get('status', None, type=int)
        master_id = args.get('master_id', None, type=int)
        user_id = args.get('user_id', None, type=int)
        # 连表要连用户表、地址表，并且查出用户名称和地址的location、address_detail
        orders = RepairOrder.query.join(UserAddress, RepairOrder.address_id == UserAddress.id).\
            join(User, RepairOrder.user_id == User.id).\
            add_columns(User.nickname, UserAddress.location, UserAddress.address_detail)
        if status is not None:
            orders = orders.filter(RepairOrder.status == status)
        if master_id is not None:
            orders = orders.filter(RepairOrder.tech_id == master_id)
        if user_id is not None:
            orders = orders.filter(RepairOrder.user_id == user_id)
        orders = orders.order_by(RepairOrder.created_at.desc()).\
            paginate(page=page, per_page=per_page, error_out=False)
        return APIResponse.success({
            'total': orders.total,
            'items': [{
                **order[0].to_dict(),
                'user_name': order[1],
                'location': order[2],
                'address_detail': order[3]
            } for order in orders.items]
        })

    @staticmethod
    def create_order(data):
        # 验证必填字段
        required_fields = ['user_id', 'asset_name', 'contact_phone']
        for field in required_fields:
            if field not in data or not data[field]:
                return APIResponse.validate_error(f'{field} is required')

        # 创建新订单
        new_order = RepairOrder(
            user_id=data.get('user_id'),
            order_id=generate_order_id(),
            address_id=data.get('address_id'),
            status=data.get('status', 0),
            security_code=data.get('security_code'),
            asset_name=data.get('asset_name'),
            damage_desc=data.get('damage_desc'),
            fault_code=data.get('fault_code'),
            fault_detail=data.get('fault_detail'),
            expected_time=data.get('expected_time'),
            contact_phone=data.get('contact_phone'),
            repair_address=data.get('repair_address'),
            remark=data.get('remark'),
            price=data.get('price', 20),
            extra_fee_id=data.get('extra_fee_id')
        )

        try:
            new_order.save()
            return APIResponse.success(new_order.to_dict(), 'Order created successfully')
        except Exception as e:
            db.session.rollback()
            print(str(e))
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def update_order(order_id, data):
        order = RepairOrder.query.filter_by(id=order_id).first()
        if not order:
            return APIResponse.not_found('Order not found')

        # 更新字段
        if 'user_id' in data:
            order.user_id = data['user_id']
        if 'address_id' in data:
            order.address_id = data['address_id']
        if 'status' in data:
            # 使用状态机处理状态转换
            state_machine = OrderStateMachine()
            state_machine.current_state = order.status  # 设置当前状态
            target_state = int(data['status'])
            if not state_machine.go_to_state(target_state):
                return APIResponse.fail(f'状态切换失败: 无法从 {state_machine.states[order.status]} 切换到 {state_machine.states.get(target_state, "无效状态")}', 10004)
            order.status = target_state
        if 'security_code' in data:
            order.security_code = data['security_code']
        if 'asset_name' in data:
            order.asset_name = data['asset_name']
        if 'damage_desc' in data:
            order.damage_desc = data['damage_desc']
        if 'fault_code' in data:
            order.fault_code = data['fault_code']
        if 'fault_detail' in data:
            order.fault_detail = data['fault_detail']
        if 'expected_time' in data:
            order.expected_time = data['expected_time']
        if 'contact_phone' in data:
            order.contact_phone = data['contact_phone']
        if 'repair_address' in data:
            order.repair_address = data['repair_address']
        if 'remark' in data:
            order.remark = data['remark']
        if 'price' in data:
            order.price = data['price']
        if 'extra_fee_id' in data:
            order.extra_fee_id = data['extra_fee_id']
        if 'tech_id' in data:
            order.tech_id = data['tech_id']

        try:
            order.save()
            return APIResponse.success(order.to_dict(), 'Order updated successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)